package com.zqj.project.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zqj.project.common.database.mybatis.conditions.Wraps;
import com.zqj.project.common.database.mybatis.conditions.query.LbqWrapper;
import com.zqj.project.common.exception.BizException;
import com.zqj.project.converter.UserConverter;
import com.zqj.project.entity.UserPO;
import com.zqj.project.factory.UserFactory;
import com.zqj.project.model.User;
import com.zqj.project.repository.UserMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * @Description: UserServiceImpl
 * @Author: 22001010704 Zhang Qijian
 * @CreateTime: 2024/11/8 15:39
 * @Version: 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public IPage<User> page(User user, IPage<User> page) {
        final Long count = this.userMapper.selectCount(UserFactory.lbqWrapper(user));
        if (Objects.equals(0L, count)) {
            return page;
        }
        page.setTotal(count);
        return page.setRecords(UserConverter.toUserModelList(this.userMapper.selectPage(new Page<>(page.getCurrent(), page.getSize(), page.getTotal()), UserFactory.lbqWrapper(user)).getRecords()));
    }

    @Override
    public User info(Long id) {
        UserPO userPo = this.userMapper.selectById(id);
        if (Objects.isNull(userPo)) {
            throw new BizException("用户不存在");
        }
        return UserConverter.toUserModel(userPo);
    }

    @Override
    public Boolean add(User user) {
        if (this.userMapper.selectCount(Wraps.<UserPO>lbQ().eq(StringUtils.isNotBlank(user.getName()), UserPO::getName, user.getName().trim())) > 0L) {
            throw new BizException("用户名称已被占用");
        }
        return this.userMapper.insert(UserConverter.toUserPo(user)) == 1;
    }

    @Override
    public Boolean edit(User user) {
        return this.userMapper.updateById(UserConverter.toUserPo(user)) == 1;
    }

    @Override
    public Boolean delete(Long id) {
        return this.userMapper.deleteById(id) == 1;
    }

    @Override
    public Boolean login(User user) {
        LbqWrapper<UserPO> lbqWrapper = Wraps.<UserPO>lbQ().eq(UserPO::getName, user.getName()).eq(UserPO::getPassword, user.getPassword());
        UserPO userPo = this.userMapper.selectOne(lbqWrapper);
        return Objects.nonNull(userPo);
    }


    @Override
    public Boolean register(User user) {
        if (this.userMapper.selectCount(Wraps.<UserPO>lbQ().eq(StringUtils.isNotBlank(user.getName()), UserPO::getName, user.getName().trim())) > 0L) {
            throw new BizException("用户名称已被占用");
        }
        return this.userMapper.insert(UserConverter.toUserPo(user)) == 1;
    }

}